package com.df.barcodescaning.ui;

import android.Manifest;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.df.barcodescaning.R;
import com.df.barcodescaning.util.CSVUtils;
import com.df.barcodescaning.util.DialogUtils;
import com.df.barcodescaning.util.FileUtils;
import com.df.barcodescaning.util.LoggerUtil;
import com.df.barcodescaning.util.MixSpeakUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.df.barcodescaning.instance.ReceivingInstances.ACTION_DF_SCAN_RESULT;
import static com.df.barcodescaning.instance.ReceivingInstances.ACTION_DF_SCAN_START_TO_APP;
import static com.df.barcodescaning.instance.ReceivingInstances.ACTION_DF_SCAN_STOP_TO_APP;
import static com.df.barcodescaning.instance.ReceivingInstances.RESULT;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "--Main--";
    private final int CODE_REQUEST_FILE_SELECT = 45521;
    private static final String PREFS_NAME = "sp_name_path_id";
    private static final String KEY_PREFS_PATH = "sp_key_path_id";
    private static final String KEY_PREFS_ID = "sp_key_selected_id";

    TextView tvTittle, tvContent;
    private TextView tvSrc;

    private MyReceiver mReceiver;
    private MixSpeakUtil mixSpeakUtil;
    //创建震动服务对象
    private Vibrator mVibrator;
    private List<String> dataList;
    private int selectIndex = -1;
    private String dataPath;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.rl_import).setOnClickListener(this);
        tvSrc = (TextView) findViewById(R.id.tv_data_src_content);
        findViewById(R.id.rl_id).setOnClickListener(this);
        tvTittle = (TextView)findViewById(R.id.tv_id_content);
        tvContent = (TextView)findViewById(R.id.tv_content_content);

        SharedPreferences sp = getUserData();
        if (sp != null) {
            dataPath = sp.getString(KEY_PREFS_PATH, "");
            if (dataPath.length() > 0) {
                tvSrc.setText(dataPath);
                dataList = CSVUtils.importCsv(new File(dataPath));
                selectIndex = sp.getInt(KEY_PREFS_ID, selectIndex);
                if (selectIndex != -1) showSelectResult(selectIndex);
            }
        }

        mReceiver = new MyReceiver();
        initPermission();
        mixSpeakUtil=MixSpeakUtil.getInstance(this);
        LoggerUtil.setLogFileName("ScanningRst");
        //获取手机震动服务
        mVibrator=(Vibrator)getApplication().getSystemService(Service.VIBRATOR_SERVICE);
    }

    @Override
    protected void onResume() {
        super.onResume();

        Intent sendIntent = new Intent(ACTION_DF_SCAN_START_TO_APP);
        sendBroadcast(sendIntent);

        IntentFilter ItFilter = new IntentFilter();
        ItFilter.addAction(ACTION_DF_SCAN_RESULT);
        registerReceiver(mReceiver, ItFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();

        Intent sendIntent = new Intent(ACTION_DF_SCAN_STOP_TO_APP);
        sendBroadcast(sendIntent);

        unregisterReceiver(mReceiver);
    }

    @Override
    protected void onDestroy() {
        saveUserData();
        super.onDestroy();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_import:
                openFileSelector();
                break;
            case R.id.rl_id:
                if (dataList != null && dataList.size() > 0) {
                    showSelectBarcodeDialog();
                } else {
                    Toast.makeText(this, getString(R.string.alert_data_null), Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    /**
     * android 6.0 以上需要动态申请权限
     */
    private void initPermission() {
        if (Build.VERSION.SDK_INT < 23) {
            return;
        }
        String[] permissions = {
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.MODIFY_AUDIO_SETTINGS,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_SETTINGS,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.CHANGE_WIFI_STATE
        };

        ArrayList<String> toApplyList = new ArrayList<String>();

        for (String perm : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
                toApplyList.add(perm);
                // 进入到这里代表没有权限.
            }
        }
        String[] tmpList = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 123);
        }

    }

    private void openFileSelector() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("text/comma-separated-values");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(Intent.createChooser(intent, "Please select a file."),
                    CODE_REQUEST_FILE_SELECT);
        } catch (android.content.ActivityNotFoundException ex) {
            // Potentially direct the user to the Market with a Dialog
            Toast.makeText(this, "Please install the file manager.", Toast.LENGTH_SHORT).show();
        }
    }

    private void showSelectBarcodeDialog() {
        String[] array = new String[dataList.size()];
//        array = dataList.toArray(array);
        for (int i = 0; i < dataList.size(); i++) {
            String[] strArr = dataList.get(i).split(",");
            array[i] = strArr[0];
        }
        new DialogUtils(this, getString(R.string.tittle_select_barcode))
            .singleChoiceDialog(array, selectIndex,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        selectIndex = i;
                    }
                },
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        /*new DialogUtils(MainActivity.this, dataList.get(selectIndex))
                            .nomalDialog(android.R.string.ok, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    showSelectResult(selectIndex);
                                }
                            }, R.string.reselect, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    showSelectBarcodeDialog();
                                }
                            });*/
                        if (selectIndex != -1) showSelectResult(selectIndex);
                    }
                });
    }

    private void showSelectResult(int index) {
//        Toast.makeText(this, index+"", Toast.LENGTH_SHORT).show();
        String result = dataList.get(index);
        String[] strArr = result.split(",");
        tvTittle.setText(strArr[0]);
        if(strArr.length > 1) {
            tvContent.setText(result.substring(result.indexOf(",")+1));
        } else {
            tvContent.setText("");
        }
    }

    private void handleScanResult(String result) {
        if (selectIndex != -1) {
            String logStr ;
            String dialogTittle;
            String dialogMsg;
//            Toast.makeText(this, tvTittle.getText().toString() + " || " + result, Toast.LENGTH_SHORT).show();
            if(tvTittle.getText().toString().equals(result)) {  //扫描成功, 条码匹配正确
                logStr = getString(R.string.rst_scan_match) + result;
                dialogTittle = getString(R.string.rst_scan_match);
                mixSpeakUtil.speak(getString(R.string.voice_alert_match));
            } else {    //条码不匹配,请确认
                mVibrator.vibrate(new long[]{100,100,100,1000},-1);
                logStr = getString(R.string.rst_scan_mismatch) + result;
                dialogTittle = getString(R.string.rst_scan_mismatch);
                mixSpeakUtil.speak(getString(R.string.voice_alert_mismatch));
            }
            dialogMsg = getString(R.string.rst_scan) + result;
            new DialogUtils(this, dialogTittle).hintDialog(dialogMsg, android.R.string.ok, null);
            LoggerUtil.writeToFile(logStr);
        }
    }


    private void saveUserData() {
        if(dataPath == null || dataPath.length() == 0 || selectIndex == -1) return;
        SharedPreferences sp = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        sp.edit().putString(KEY_PREFS_PATH, dataPath).putInt(KEY_PREFS_ID, selectIndex).commit();
    }

    private SharedPreferences getUserData() {
        return getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_REQUEST_FILE_SELECT && resultCode == RESULT_OK) {
            // Get the Uri of the selected file
            Uri uri = data.getData();
            //uri---->>> content://com.android.externalstorage.documents/document/primary%3ADownload%2Fsaf.csv
            Log.i(TAG, "uri---->>> " + uri.toString());
            //path--->>> /storage/emulated/0/Download/saf.csv
            dataPath = FileUtils.getRealFilePath(this, uri);
            tvSrc.setText(dataPath);
            Log.i(TAG, "path--->>> " + dataPath);
//            parseCSV(path);
            dataList = CSVUtils.importCsv(new File(dataPath));
            if (dataList.size() > 0) {
                showSelectBarcodeDialog();
            } else {
                Toast.makeText(this, getString(R.string.alert_data_err), Toast.LENGTH_SHORT).show();
            }
        }
    }

    private class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equalsIgnoreCase(ACTION_DF_SCAN_RESULT)) {
                String code = intent.getStringExtra(RESULT);
                code = code.trim();
                handleScanResult(code);
            }
        }
    };
}
